package sany.iec.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import sany.iec.config.GlobalVariable;
import sany.iec.entity.ServerEntity;
import sany.iec.enums.EnableEnum;
import sany.iec.enums.ServerType;
import sany.iec.service.ServerService;
import sany.iec.service.WebService;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author : 托马斯
 * @Date : 2025/7/8 9:04
 * @Description :
 */
@Service
@Slf4j
public class WebServiceImpl implements WebService {

    @Resource
    private ServerService serverService;

    @Override
    public Object stopOrStart(int port, int flag) {
        AtomicReference<ServerEntity> ser = new AtomicReference<>();
        GlobalVariable.SERVER_LIST.forEach(server -> {
            if (server.getPort() == port) {
                ser.set(server);
            }
        });
        if (ser.get() == null) {
            return "不存在此端口的服务。";
        }
        ServerEntity entity = ser.get();
        try {
            if (flag == 1) {
                // 开启
                if (entity.getServerType().equals(ServerType.MODBUS)) {
                    if (entity.getModbusServerSet() == null) {
                        serverService.startServer(entity);
                    }
                    log.info("该MODBUS服务已经开启: {}", port);
                    return String.format("该MODBUS服务已经开启: %d", port);
                } else {
                    if (entity.getIEC104Server() == null) {
                        serverService.startServer(entity);
                    }
                    log.info("该IEC104服务已经开启: {}", port);
                    return String.format("该IEC104服务已经开启: %d", port);
                }
            } else {
                // 关闭
                if (entity.getServerType().equals(ServerType.MODBUS)) {
                    if (entity.getModbusServerSet() != null) {
                        serverService.stopServer(entity);
                    }
                    log.info("该MODBUS服务已经停止: {}", port);
                    return String.format("该MODBUS服务已经停止: %d", port);
                } else {
                    if (entity.getIEC104Server() != null) {
                        serverService.stopServer(entity);
                    }
                    log.info("该IEC104服务已经停止: {}", port);
                    return String.format("该IEC104服务已经停止: %d", port);
                }
            }
        } catch (Exception e) {
            log.error("操作服务失败。", e);
        }
        return null;
    }

}
